package com.cxq.boot.controller;

import com.cxq.boot.dto.AccessTokenDTO;
import com.cxq.boot.strategy.LoginUserInfo;
import com.cxq.boot.strategy.UserStrategy;
import com.cxq.boot.strategy.UserStrategyFactory;
import com.cxq.boot.strategy.dto.GithubUser;
import com.cxq.boot.model.User;
import com.cxq.boot.provider.GitHubProvider;
import com.cxq.boot.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
@Slf4j
public class AuthorizeController {
    @Autowired
    private UserStrategyFactory userStrategyFactory;

    @Autowired
    GitHubProvider gitHubProvider;

    @Value("${github.client.id}")
    private String clientId;
    @Value("${github.client.secret}")
    private String clientSecret;
    @Value("${github.redirect.uri}")
    private String redirectUri;

    @Autowired
    private UserService userService;

    @GetMapping("/callback/{type}")
    public String newCallback(@PathVariable("type") String type,
                              @RequestParam("code") String code,
                              @RequestParam(value = "state",required = false) String state,
                              HttpServletResponse response) {
        UserStrategy userStrategy = userStrategyFactory.getStrategy(type);
        LoginUserInfo loginUserInfo = userStrategy.getUser(code, state);
        System.out.println(loginUserInfo);

        if (loginUserInfo != null && loginUserInfo.getId() != null) {
            User user = new User();
            String token = UUID.randomUUID().toString();
            user.setToken(token);
            user.setName(loginUserInfo.getName());
            user.setAccountId(String.valueOf(loginUserInfo.getId()));
            user.setAvatarUrl(loginUserInfo.getAvatarUrl());
            user.setType(type);
            userService.createOrUpdate(user);

            //将token存入cookie
            Cookie cookie = new Cookie("token", token);
            cookie.setMaxAge(60 * 60 * 24 * 30 * 6);//设置生命周期
            cookie.setPath("/");
            response.addCookie(cookie);
            //登录成功，写 session 和 cookie
            //request.getSession().setAttribute("user", githubUser);//使用首页请求从数据库查数据判断是否登录
            return "redirect:/";
        } else {
            //打印日志
            log.error("callback get user error,{}",loginUserInfo);
            //登录失败，重新登录
            return "redirect:/";
        }
    }

    /**
     * 获取 GitHub 用户进行登录，并将用户信息(设置一个token) 保存到数据库
     *
     * @return 首页
     */
    @GetMapping("/callback")
    public String callback(@RequestParam("code") String code,
                           @RequestParam("state") String state,
                           HttpServletResponse response) {
        AccessTokenDTO accessTokenDTO = new AccessTokenDTO();
        accessTokenDTO.setClient_id(clientId);
        //第二个：0f1b1655de7f8c6ba2736fdf6fca0f7159a367f6
        accessTokenDTO.setClient_secret(clientSecret);
        accessTokenDTO.setCode(code);
        accessTokenDTO.setRedirect_uri(redirectUri);
        accessTokenDTO.setState(state);
        String accessToken = gitHubProvider.getAccessToken(accessTokenDTO);
        GithubUser githubUser = gitHubProvider.getUser(accessToken);

        if (githubUser != null && githubUser.getId() != null) {
            User user = new User();
            String token = UUID.randomUUID().toString();
            user.setToken(token);
            user.setName(githubUser.getName());
            user.setAccountId(String.valueOf(githubUser.getId()));
            user.setAvatarUrl(githubUser.getAvatarUrl());
            userService.createOrUpdate(user);
            response.addCookie(new Cookie("token", token));
            //登录成功，写 session 和 cookie
            //request.getSession().setAttribute("user", githubUser);//使用首页请求从数据库查数据判断是否登录
            return "redirect:/";
        } else {
            //登录失败，重新登录
            return "redirect:/";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request,
                         HttpServletResponse response) {
        request.getSession().removeAttribute("user");
        Cookie cookie = new Cookie("token", null);
        cookie.setMaxAge(0);//立即删除
        //cookie.setPath("/");
        response.addCookie(cookie);
        return "redirect:/";
    }
}
